/**
 * Created by Delicate on 2018/1/3.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    ScrollView,

} from 'react-native';

import Picker from 'react-native-picker'

import {
    FormStatus,
    FormEvent,
    SubmitBtn,
    DefaultFieldType,
    DefaultField,
    DefaultInput,
    DefaultTextArea,
    DefaultLabel,
    EventPicker
} from '../../components/Form'
import NavBar from '../../components/NavBarView'
import {NatureOptions} from '../../config/dict/Nature'
import {DateOptions} from '../../config/dict/Date'
import ManagerService from '../../services/Manager'

let _self;

let validRule = {};
let IndustryData = [];
let regionData = [];

class Views extends React.Component {

    constructor(props) {
        super(props);
        _self = this;
        this.state = {
            formStatus: FormStatus.EDIT,
            form: {
                institution_name: '',
                busniess_number: '',
                legal_name: '',
                industry_type: '',
                nature: '',
                registered_capital: '',
                establishment_date: '',
                province: '',
                city: '',
                district: '',
                detail_address: '',
                business: '',
                advantage: ''
            },
            calcYears: '',
            readOnly: false
        };
        const params = this.props.navigation.state.params;
        this.state.readOnly = params.readOnly;
        this.state.form = {
            ...this.state.form,
            ...params.detail
        };
        if (this.state.form.establishment_date) {
            this.state.form.establishment_date = format.date(this.state.form.establishment_date);
            const establishment_date_year = this.state.form.establishment_date.substr(0, 4);
            this.state.calcYears = new Date().getFullYear() - establishment_date_year * 1 > 0 ? new Date().getFullYear() - establishment_date_year * 1 : 1
        }
        validRule = {...params.validRule};
        IndustryData = params.industry;
        regionData = params.region;
    }

    componentWillMount() {

    }

    componentDidMount() {

    }

    componentWillUnmount() {
        if (Picker.isPickerShow) {
            Picker.hide();
        }
    }

    //input改变触发
    inputChange(key, value) {
        let form = _self.state.form;
        form[key] = value;
        _self.setState({form}, () => {
            setTimeout(() => {
                _self.setState({
                    formStatus: FormEvent.isCompleted(validRule, _self.state.form)
                })
            }, 200);
        });
    }

    //企业性质选择及处理
    selectNature() {
        FormEvent.picker({
            data: NatureOptions,
            title: '企业性质',
            handleConfirm(data) {
                _self.inputChange('nature', data.join('-'));
            }
        });
    }

    //所属行业选择及处理
    selectIndustry() {
        FormEvent.picker({
            data: IndustryData,
            title: '所属行业',
            handleConfirm(data) {
                _self.inputChange('industry_type', data.join('-'));
            }
        });
    }

    //成立日期选择及处理 & 成立年限
    selectDate() {
        FormEvent.picker({
            data: DateOptions.slice(0, (new Date().getFullYear() - 1948)),
            title: '成立日期',
            handleConfirm(data) {
                _self.setState({
                    calcYears: new Date().getFullYear() - data[0] * 1 > 0 ? new Date().getFullYear() - data[0] * 1 : 1
                })
                _self.inputChange('establishment_date', data.join('-'));
            }
        });
    }

    //公司所在地选择及处理
    selectRegion() {
        FormEvent.picker({
            data: regionData,
            title: '公司所在地',
            handleConfirm(data) {
                _self.inputChange('province', data[0]);
                _self.inputChange('city', data[1]);
                _self.inputChange('district', data[2]);
            }
        });
    }

    async submit() {
        const {result, message} = FormEvent.isValid(validRule, _self.state.form);
        if(result){
            const {result, message} = await ManagerService.baseSubmit({params: _self.state.form});
            if(result) {
                Toast.show("提交成功");
                _self.props.navigation.state.params.refresh();
                setTimeout(()=>{
                    _self.props.navigation.goBack();
                },400);
            }else {
                Toast.show(message);
            }
        }else{
            Toast.show(message);
        }
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar
                    host={this}
                    title="企业基本信息"/>
                <ScrollView style={styles.container}>
                    <DefaultField text="企业名称">
                        {
                            this.state.readOnly ?
                                <DefaultLabel inputValue={this.state.form.institution_name}/> :
                                <DefaultInput
                                    onChangeText={(text) => this.inputChange('institution_name', text)}
                                    maxLength={50}
                                    inputValue={this.state.form.institution_name}
                                    placeholder="请输入企业名称"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField text="信用代码">
                        {
                            this.state.readOnly ?
                                <DefaultLabel inputValue={this.state.form.busniess_number}/>:
                                <DefaultInput
                                    onChangeText={(text) => this.inputChange('busniess_number', text)}
                                    maxLength={18}
                                    inputValue={this.state.form.busniess_number}
                                    placeholder="请输入18位统一社会信用代码"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField text="法定代表人">
                        {
                            this.state.readOnly ?
                                <DefaultLabel inputValue={this.state.form.legal_name}/>:
                                <DefaultInput
                                    onChangeText={(text) => this.inputChange('legal_name', text)}
                                    maxLength={10}
                                    inputValue={this.state.form.legal_name}
                                    placeholder="请输入法定代表人名称"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField text="所属行业">
                        {
                            this.state.readOnly ?
                                <DefaultLabel inputValue={this.state.form.industry_type}/> :
                                <DefaultLabel
                                    onPress={() => this.selectIndustry()}
                                    rightIcon={require('../../sources/icon_global_go.png')}
                                    inputValue={this.state.form.industry_type}
                                    placeholder="请选择所属行业"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField text="企业性质">
                        {
                            this.state.readOnly ?
                                <DefaultLabel inputValue={this.state.form.nature}/> :
                                <DefaultLabel
                                    onPress={() => this.selectNature()}
                                    rightIcon={require('../../sources/icon_global_go.png')}
                                    inputValue={this.state.form.nature}
                                    placeholder="请选择企业性质"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField text="注册资本">
                        {
                            this.state.readOnly ?
                                <DefaultLabel suffix="万元" inputValue={this.state.form.registered_capital}/> :
                                <DefaultInput
                                    suffix="万元"
                                    onChangeText={(text) => this.inputChange('registered_capital', text)}
                                    maxLength={13}
                                    inputValue={this.state.form.registered_capital}
                                    placeholder="请输入注册资本"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField text="成立日期">
                        {
                            this.state.readOnly ?
                                <DefaultLabel inputValue={this.state.form.establishment_date}/> :
                                <DefaultLabel
                                    onPress={() => this.selectDate()}
                                    rightIcon={require('../../sources/icon_global_go.png')}
                                    inputValue={this.state.form.establishment_date}
                                    placeholder="请选择成立日期"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    {
                        this.state.form.establishment_date ?
                            <DefaultField text="成立年限">
                                <DefaultLabel
                                    suffix="年"
                                    inputValue={this.state.calcYears}
                                    placeholder="自动计算成立年限"
                                    control={this.state.formStatus}/>
                            </DefaultField> :
                            <View/>
                    }
                    <DefaultField text="公司所在地">
                        {
                            this.state.readOnly ?
                                <DefaultLabel inputValue={
                                    this.state.form.province ?
                                        `${this.state.form.province} - ${this.state.form.city} - ${this.state.form.district}` :
                                        ''
                                }/> :
                                <DefaultLabel
                                    onPress={() => this.selectRegion()}
                                    rightIcon={require('../../sources/icon_global_go.png')}
                                    inputValue={
                                        this.state.form.province ?
                                            `${this.state.form.province} - ${this.state.form.city} - ${this.state.form.district}` :
                                            ''
                                    }
                                    placeholder="请选择公司所在地"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField type={DefaultFieldType.BLOCK} text="详细地址">
                        {
                            this.state.readOnly ?
                                <DefaultLabel textStyle={styles.labelTextAlign}
                                              inputValue={this.state.form.detail_address}/> :
                                <DefaultTextArea
                                    onChangeText={(text) => this.inputChange('detail_address', text)}
                                    maxLength={50}
                                    inputValue={this.state.form.detail_address}
                                    placeholder="请输入详细地址"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField type={DefaultFieldType.BLOCK} text="主营业务">
                        {
                            this.state.readOnly ?
                                <DefaultLabel textStyle={styles.labelTextAlign}
                                              inputValue={this.state.form.business}/> :
                                <DefaultTextArea
                                    onChangeText={(text) => this.inputChange('business', text)}
                                    maxLength={1000}
                                    inputValue={this.state.form.business}
                                    placeholder="请输入主营业务"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                    <DefaultField type={DefaultFieldType.BLOCK} text="公司优势">
                        {
                            this.state.readOnly ?
                                <DefaultLabel textStyle={styles.labelTextAlign}
                                              inputValue={this.state.form.advantage}/> :
                                <DefaultTextArea
                                    onChangeText={(text) => this.inputChange('advantage', text)}
                                    maxLength={1000}
                                    inputValue={this.state.form.advantage}
                                    placeholder="请输入公司优势(非必填)"
                                    control={this.state.formStatus}/>
                        }
                    </DefaultField>
                </ScrollView>
                {
                    this.state.readOnly ?
                        <View/> :
                        <View style={styles.btnBox}>
                            <SubmitBtn
                                style={styles.btn}
                                onPress={() => this.submit()}
                                control={this.state.formStatus}
                                text="保存"/>
                        </View>
                }
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#fff'
    },
    btnBox: {
        paddingHorizontal: layout.GAP_HORIZONTAL_SMALL,
        paddingVertical: layout.GAP_VERTICAL_SMALL,
        backgroundColor: '#fff'
    },
    btn: {
        marginTop: 0,
        height: layout.height(90)
    },
    labelTextAlign: {
        textAlign: 'left'
    }
})

//路由
const AuthForm = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'AuthForm',
    sign: true
};

export default AuthForm;